package com.blog.wu.myblog.activemq.queue;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

/**
 * @Author wuyanshen
 * @Date 2018-12-25 1:33 PM
 * @Discription 点对点通讯（queue）一对一 只能有一个消费者 原生方式activeMQ 消费者
 */
public class ActiveMqConsumer {

    public static void main(String[] args) {

        try {
            //获取mq连接工厂
            ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(ActiveMQConnection.DEFAULT_USER, ActiveMQConnection.DEFAULT_PASSWORD, "tcp://127.0.0.1:61616");
            //创建连接
            Connection connection = connectionFactory.createConnection();
            //启动连接
            connection.start();
            //创建会话工厂
            //Session.AUTO_ACKNOWLEDGE 自动签收
            //Session.CLIENT_ACKNOWLEDGE 手动签收
            //Session.DUPS_OK_ACKNOWLEDGE 不用签收 这种不好，当网络延迟情况会产生幂等性问题（数据不一致）
            //Boolean.FALSE 关闭事物
            //Boolean.TRUE 开启事物

            Session session = connection.createSession(Boolean.TRUE, Session.DUPS_OK_ACKNOWLEDGE);
            //创建队列
            Destination destination = session.createQueue("myblog_queue");
            MessageConsumer consumer = session.createConsumer(destination);
            //监听消息
            while (true) {
                TextMessage textMessage = (TextMessage) consumer.receive();
                if (textMessage != null) {
                    String text = textMessage.getText();
                    System.out.println("消费者获取消息：" + text);

                    //手动签收
//                    textMessage.acknowledge();

                    //提交事物
                    session.commit();
                } else {
                    break;
                }
            }
            System.out.println("消费者消费消息完毕");

        } catch (JMSException e) {
            e.printStackTrace();
        }
    }

}
